//
//  RowView.swift
//  
//
//  Created by 孙长坦 on 2022/6/17.
//

import Foundation
import UIKit

class RowView: UIView {
    private let padding: CGFloat = 8
    private let spacing: CGFloat = 0
    
    override var intrinsicContentSize: CGSize {
        var width: CGFloat = subviews.reduce(0) { partialResult, childView in
            let size = childView.sizeThatFits(CGSize(width: UIView.noIntrinsicMetric,
                                                     height: UIView.noIntrinsicMetric))
            return partialResult + size.width + padding
        }
        
        width += !subviews.isEmpty ? spacing * CGFloat((subviews.count - 1)) : 0.0
        
        return CGSize(width: width, height: UIView.noIntrinsicMetric)
    }
    
    override init(frame: CGRect = .zero) {
        super.init(frame: frame)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        var x: CGFloat = 0
        subviews.enumerated().forEach { element in
            let size = element.element.sizeThatFits(CGSize(width: UIView.noIntrinsicMetric,
                                                           height: UIView.noIntrinsicMetric))
            element.element.frame = CGRect(x: x, y: 0,
                                           width: size.width + padding,
                                           height: bounds.height)
            
            x += element.element.frame.width
            if element.offset != subviews.count - 1 {
                x += spacing
            }
        }
    }
    
    override func sizeThatFits(_ size: CGSize) -> CGSize {
        return intrinsicContentSize
    }
}
